<template>
  <div class="wrap">
    <div class="d-flex align-items-center d-top">
      <label class="el-form-item__label">{{ $t('message.MeasureCableDlg.checkType') }}：</label>
      <el-radio-group v-model="params.checkTypeSelected">
        <el-radio class="fix-width-radio"
                  v-for="(item,index) in params.checkTypeRadioList"
                  :label="item.value"
                  key="index">
          {{item.text}}
        </el-radio>
      </el-radio-group>
    </div>

    <div class="d-flex align-items-center d-top">
      <label class="el-form-item__label">{{ $t('message.MeasureCableDlg.branchableAssembly') }}：</label>
      <query-list :tipMsg="$t('message.MeasureCableDlg.branchableAssembly')"
                  v-model="params.branchableAssembly"
                  :active="params.queryListActiveMap.branchableAssembly"
                  @switchQuery="switchQuery('branchableAssembly')"/>
    </div>

    <div class="d-flex align-items-center d-top">
      <label class="el-form-item__label">{{ $t('message.MeasureCableDlg.environmentAssembly') }}：</label>
      <query-list :tipMsg="$t('message.MeasureCableDlg.environmentAssembly')"
                  v-model="params.environmentAssembly"
                  :active="params.queryListActiveMap.environmentAssembly"
                  @switchQuery="switchQuery('environmentAssembly')"/>
    </div>

    <div class="d-flex align-items-center d-top">
      <label class="el-form-item__label">{{ $t('message.MeasureCableDlg.measureType') }}：</label>
      <el-radio-group v-model="params.measureTypeSelected">
        <el-radio class="fix-width-radio"
                  v-for="(item,index) in params.measureTypeRadioList"
                  :label="item.value"
                  key="index">
          {{item.text}}
        </el-radio>
      </el-radio-group>
    </div>

    <div class="d-flex align-items-center d-top">
      <label class="el-form-item__label">{{ $t('message.MeasureCableDlg.exportType') }}：</label>
      <el-radio-group v-model="params.exportTypeSelected">
        <el-radio class="fix-width-radio"
                  v-for="(item,index) in params.exportTypeRadioList"
                  :label="item.value"
                  key="index">
          {{item.text}}
        </el-radio>
      </el-radio-group>
    </div>

    <div class="d-flex align-items-center d-top" v-if="!params.checkTypeSelected">
      <label class="el-form-item__label">{{ $t('message.MeasureCableDlg.distance') }}：</label>
      <el-input v-model="params.distance" min="0" step="5" type="number"/>
      <label class="label">mm</label>
    </div>

<!--    <div class="d-flex align-items-center">-->
<!--      <el-table ref="sectionList"-->
<!--                :data="params.partDistanceInfo"-->
<!--                highlight-current-row-->
<!--                @current-change="handleCurrentChange"-->
<!--                tooltip-effect="dark"-->
<!--                style="width: 100%;margin-top: 5px"-->
<!--                border size="small">-->
<!--        <el-table-column prop="index"-->
<!--                         :label="$t('message.MeasureCableDlg.no')"-->
<!--                         min-width="50">-->
<!--          <template v-slot="scope">-->
<!--            <label class="label">{{ scope.row.index + 1 }}</label>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="startSegment"-->
<!--                         :label="$t('message.MeasureCableDlg.segmentStart')"-->
<!--                         min-width="180">-->
<!--          <template v-slot="scope">-->
<!--            <label class="label">{{ scope.row.startSegment }}</label>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="endSegment"-->
<!--                         :label="$t('message.MeasureCableDlg.segmentEnd')"-->
<!--                         min-width="180">-->
<!--          <template v-slot="scope">-->
<!--            <label class="label">{{ scope.row.endSegment }}</label>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="minDistance"-->
<!--                         :label="$t('message.MeasureCableDlg.minDistance')"-->
<!--                         min-width="100">-->
<!--          <template v-slot="scope">-->
<!--            <label class="label">{{ scope.row.minDistance }}</label>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <!--        <el-table-column prop="pointStart"-->
        <!--                         :label="$t('message.MeasureCableDlg.pointStart')"-->
        <!--                         min-width="200">-->
        <!--          <template v-slot="scope">-->
        <!--            <label class="label">{{ scope.row.pointStart }}</label>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column prop="pointEnd"-->
        <!--                         :label="$t('message.MeasureCableDlg.pointEnd')"-->
        <!--                         min-width="200">-->
        <!--          <template v-slot="scope">-->
        <!--            <label class="label">{{ scope.row.pointEnd }}</label>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
<!--      </el-table>-->
<!--    </div>-->

    <div class="btn">
<!--      <el-button-->
<!--          type="primary"-->
<!--          size="small"-->
<!--          @click="confirm">-->
<!--        {{ $t('message.MeasureCableDlg.measure') }}-->
<!--      </el-button>-->

      <el-button
          type="primary"
          size="small"
          :disabled="!isExport"
          @click="exportData">
        {{ $t('message.MeasureCableDlg.export') }}
      </el-button>

      <el-button
          size="small"
          @click="cancel">
        {{ $t('message.MeasureCableDlg.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import DialogMixin from "../DialogMixin";
import {measureCableCommand} from "../../../command/MeasureCableCommand";
import * as XLSX from "xlsx"
import {saveAs} from 'file-saver'
import {v4 as uuidv4} from 'uuid';
import {i18n} from "../../js/util/I18n";
import {request} from "../../../util/Request";

export default {
  mixins: [DialogMixin],
  data() {
    return {
      params: {
        branchableAssembly: [],
        environmentAssembly: [],
        partDistanceInfo: [],
        queryListActiveMap: {
          branchableAssembly: 1,
          environmentAssembly: 0
        },
        distance: 100,
        checkTypeRadioList: [
          {
            text: i18n.getMessage('message.MeasureCableDlg.normalCheck'),
            value: 0,
          },
          {
            text: i18n.getMessage('message.MeasureCableDlg.separationCodeCheck'),
            value: 1,
          }
        ],
        checkTypeSelected: 0,
        measureTypeRadioList: [
          {
            text: i18n.getMessage('message.MeasureCableDlg.betweenSegments'),
            value: 0,
          },
          {
            text: i18n.getMessage('message.MeasureCableDlg.segmentsAndEnv'),
            value: 1,
          },
          {
            text: i18n.getMessage('message.MeasureCableDlg.allType'),
            value: 2,
          }
        ],
        measureTypeSelected: 0,
        exportTypeRadioList: [
          {
            text: i18n.getMessage('message.MeasureCableDlg.lessThanMinDistance'),
            value: 0,
          },
          {
            text: i18n.getMessage('message.MeasureCableDlg.allDistance'),
            value: 1,
          }
        ],
        exportTypeSelected: 0
      }
    }
  },

  mounted() {
    measureCableCommand.init(600, 600, 300, () => {
      this.handlePickInstance();
    });
  },

  methods: {
    handlePickInstance() {
      measureCableCommand.handlePickInstance((res) => {
        let insItem = res?.instance;
        if (insItem != null && insItem?.length > 0) {
          if (this.params.queryListActiveMap.branchableAssembly === 1) {
            //this.params.branchableAssembly.splice(0);
            if (!this.checkBranchableAssemblyData(insItem[0])) {
              if(!this.params.branchableAssembly.find(item=>item?.id === insItem[0]?.id)){
                this.params.branchableAssembly.push(insItem[0]);
              }
            }
          }

          if (this.params.queryListActiveMap.environmentAssembly === 1) {
            //this.params.environmentAssembly.splice(0);
            if (!this.checkEnvironmentAssemblyData(insItem[0])) {
              if(!this.params.environmentAssembly.find(item=>item?.id === insItem[0]?.id)){
                this.params.environmentAssembly.push(insItem[0]);
              }
            }
          }
        }
      });
    },

    // 检查选择线束装配数据
    checkBranchableAssemblyData(insItem) {
      if (this.params.environmentAssembly.find(item => item?.id === insItem?.id)) {
        measureCableCommand.eventBusAlertMsg("本次选择的线束装配已经存在于环境装配中，不可选择！", "warning");
        return true;
      } else if (insItem?.type === "part") {
        measureCableCommand.eventBusAlertMsg("当前选择是零件，请选择装配节点！", "warning");
        return true;
      } else {
        return false;
      }
    },

    // 检查选择环境装配数据
    checkEnvironmentAssemblyData(insItem) {
      if (this.params.branchableAssembly.find(item => item?.id === insItem?.id)) {
        measureCableCommand.eventBusAlertMsg("本次选择的环境装配已经存在于线束装配中，不可选择！", "warning");
        return true;
      } else if (insItem?.type === "part") {
        measureCableCommand.eventBusAlertMsg("当前选择是零件，请选择装配节点！", "warning");
        return true;
      } else {
        return false;
      }
    },

    //导出excel
    async exportData() {
      measureCableCommand.openLoading("正在进行测量检查...");
      let result = await this.checkPartsDistance();

      // let data = [];
      // let strTitleLine = ["序号", "路径1", "路径2", "距离(mm)", "点1", "点2", "检查类型", "测量类型","线束隔离代码"];
      // data.push(strTitleLine);
      // let id = 1;
      // result.forEach(item => {
      //   let strLine = [];
      //   //strLine.push(item.index + 1);
      //   strLine.push(id);
      //   strLine.push(item.startSegment);
      //   strLine.push(item.endSegment);
      //   strLine.push(item.minDistance);
      //   strLine.push(item.pointStart);
      //   strLine.push(item.pointEnd);
      //   strLine.push(item.checkType);
      //   strLine.push(item.seperationCode);
      //   data.push(strLine);
      //   id++;
      // });
      //
      // if (data?.length > 0) {
      //   let workSheet = XLSX.utils.aoa_to_sheet(data);
      //   let workBook = XLSX.utils.book_new();
      //   XLSX.utils.book_append_sheet(workBook, workSheet, "线束距离检查");
      //   let excelBuffer = XLSX.write(workBook, {bookType: 'xlsx', type: 'array'});
      //   let dataBlob = new Blob([excelBuffer], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
      //   saveAs(dataBlob, '线束测量导出结果.xlsx');
      // } else {
      //   measureCableCommand.eventBusAlertMsg("无测量结果数据，无法导出数据文件", "waring");
      // }

      measureCableCommand.closeLoading();
    },

    async checkPartsDistance(){
      // 前端距离检查
      console.log("开始前端距离检查。");
      let checkResult = await measureCableCommand.distanceCheck(this.params.branchableAssembly,
          this.params.environmentAssembly,
          this.params.checkTypeSelected,
          this.params.measureTypeSelected);
      console.log("前端距离结束，checkResult=");
      console.log(checkResult);
      if(checkResult?.length > 0){
        // 后端处理数据
        this.downLoadCheckFile(checkResult, res => {
          if(res?.length > 0){
            measureCableCommand.eventBusAlertMsg("线束测量结果导出成功！","success");
          }
        });
      } else {
        measureCableCommand.eventBusAlertMsg("测量数据不全，无法进行测量计算！","warning");
      }
      return checkResult;
    },

    // 后端处理及下载数据
    downLoadCheckFile(measureData, callback) {
      let requestData = {
        "userName": "admin",
        "checkType": this.params.checkTypeSelected,
        "measureType": this.params.measureTypeSelected,
        "exportType": this.params.exportTypeSelected,
        "minDistance": this.params.distance,
        "measureData": measureData
      };

      const traceId = uuidv4();
      let config = {
        responseType: 'blob',
        timeout: 100000,
        headers:{
          'Content-Type':'application/json',
          'x-trace-id': traceId
        }
      };

      let url = 'segmentMeasure/exportBom';
      request.post(url, requestData, config).then(res => {
        if (res?.data?.size !== 0) {
          //写入浏览器进行下载
          const uri = window.URL.createObjectURL(new Blob([res.data]));
          const link = document.createElement('a');
          link.href = uri;
          link.setAttribute('download', '线束测量导出结果.xlsx');
          document.body.appendChild(link);
          link.click();
          link.remove();
          window.URL.revokeObjectURL(uri);
          callback("导出成功!")
        } else {
          console.log("导出失败, res:", res);
        }
      });
    },

    cancel() {
      measureCableCommand.closeActiveCmd();
    },

    //选中一行数据
    handleCurrentChange(val) {
      this.selectRow = val;
    },

    switchQuery(name) {
      for (const key in this.params.queryListActiveMap) {
        if (key === name) {
          this.params.queryListActiveMap[key] = 1;
        } else {
          this.params.queryListActiveMap[key] = 0;
        }
      }
    },

    changePluginContainerHeight() {
      measureCableCommand.changePluginContainerHeight({
        minWidth: 600,
        maxHeight: this.$el.clientHeight,
        width: 600
      })
    }
  },

  watch: {
    "params.branchableAssembly": function () {
      // if (this.params.branchableAssembly.length === 1) {
      //   this.switchQuery("environmentAssembly");
      // }
    }
  },

  computed: {
    isExport() {
      if (this.params.measureTypeSelected === 0) {
        if (this.params?.checkTypeSelected === 0) {
          if (this.params.branchableAssembly?.length > 0 &&
              this.params.distance >= 0) {
            return true;
          } else {
            return false;
          }
        } else {
          if (this.params.branchableAssembly?.length > 0) {
            return true;
          } else {
            return false;
          }
        }
      }
      if (this.params.measureTypeSelected > 0) {
        if (this.params?.checkTypeSelected === 0) {
          if (this.params.branchableAssembly?.length > 0 &&
              this.params.environmentAssembly?.length > 0 &&
              this.params.distance >= 0) {
            return true;
          } else {
            return false;
          }
        } else {
          if (this.params.branchableAssembly?.length > 0 &&
              this.params.environmentAssembly?.length > 0) {
            return true;
          } else {
            return false;
          }
        }
      }
    }
  }
}

</script>

<style scoped>
.wrap {
  font-size: 12px;
  margin-left: 10px;
  //width: 500px;
}

.d-top{
  //width: 550px;
}
.fix-width-radio{
  width: 140px;
}
</style>